
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wch/model/login_custom.dart';
import 'package:wch/native/net_business.dart';
import 'package:wch/page/match_device.dart';
import 'package:wch/utils/log_utils.dart';
import 'package:wch/widget/padding_widget.dart';
import '../constant/event_bus_global.dart';
import '../constant/resource_constant.dart';
import '../constant/text_constant.dart';
import '../utils/toast_utils.dart';
import 'common_widget.dart';
//
//登录组件
//

class LoginTypeWidget extends StatefulWidget {
  LoginTypeWidget({Key? key, required this.width, required this.loginEntity, required this.focusIndex, this.isSendCodeEnable = true}) : super(key: key);

  final double width;
  final LoginCustomModel loginEntity;
  final int focusIndex;
  ///验证码按钮的可用性
  bool isSendCodeEnable;

  @override
  State<LoginTypeWidget> createState() => _LoginTypeWidgetState();
}

class _LoginTypeWidgetState extends State<LoginTypeWidget> {

  late ScrollController scrollController;
  bool isFirst = true;
  int lastPage = 0;

  final FocusNode _codePhoneFocusMode = FocusNode();
  final FocusNode _passPhoneFocusMode = FocusNode();
  final FocusNode _codeCodeFocusMode = FocusNode();
  final FocusNode _passPassFocusMode = FocusNode();

  StreamSubscription? keyboardSubscription;


  @override
  void dispose() {
    super.dispose();
    keyboardSubscription?.cancel();
  }

  @override
  void initState() {
    scrollController = ScrollController();

    globalEventBus.on<LoginCustomModel>().listen((event) {
      if (event.isHideKeyboard){
        LogUtils.log('hide keyboard1');
        _passPhoneFocusMode.unfocus();
        _codePhoneFocusMode.unfocus();
        _codeCodeFocusMode.unfocus();
        _passPassFocusMode.unfocus();
      } else if (event.selectType == 0) {
        LogUtils.log('hide keyboard2');
        _passPhoneFocusMode.requestFocus();
      } else if (event.selectType == 1){
        LogUtils.log('hide keyboard3');
        _codePhoneFocusMode.requestFocus();
      }
    });
  }

  @override
  Widget build(BuildContext context) {

    if (!isFirst) {
      if (widget.loginEntity.selectType == 0) {
        if (lastPage == 1) {
          scrollController.animateTo(0, duration: const Duration(milliseconds: 500), curve: Curves.easeIn);
        }
      } else {
        if (lastPage == 0) {
          scrollController.animateTo(widget.width/2, duration: const Duration(milliseconds: 500), curve: Curves.easeIn);
        }
      }
    }

    lastPage = widget.loginEntity.selectType;
    isFirst = false;

    return Material(
      color: Colors.transparent,
      child: SingleChildScrollView(
        controller: scrollController,

        physics: const NeverScrollableScrollPhysics(),
        scrollDirection: Axis.horizontal,
        child: Row(
          children: [
            SizedBox(
              width: widget.width/2,
              child: Column(
                children: [
                  InputMobile(callback: (index, text) {
                    widget.loginEntity.name = text;
                    widget.loginEntity.update();
                  }, focusNode: _passPhoneFocusMode),
                  InputPass(callback: (index, text){
                    widget.loginEntity.pass = text;
                    widget.loginEntity.update();
                  }, node: _passPassFocusMode,)
                ],
              ),
            ),
            SizedBox(
              width: widget.width/2,
              child: Column(
                children: [
                  InputMobile(callback: (index, text) {
                    widget.loginEntity.name = text;
                    widget.loginEntity.update();
                  }, focusNode: _codePhoneFocusMode),
                  InputValidCode(callback: (index, text){
                    if (index == -1) {
                      _sendCodeLogic(widget.loginEntity);
                    }
                    widget.loginEntity.code = text;
                    widget.loginEntity.update();
                  }, isEnabled: widget.isSendCodeEnable, node: _codeCodeFocusMode,)
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///发送验证码
  void _sendCodeLogic(LoginCustomModel entity) {
    NetBusiness().sendCode(codeType: 'LOGIN', mobile: entity.name!).then((value) {
      if (value) {
        ToastUtils.showToast(msg: '已发送验证码，请查收');
        globalEventBus.fire(RefreshSendCodeModel());
      }
    });
  }
}

class RefreshSendCodeModel {

}

///手机输入框
class InputMobile extends StatefulWidget {
  InputMobile({Key? key, this.callback, this.focusNode, this.hintText = inputPhoneHint}) : super(key: key);
  ///callback
  ///(len:int content:String)
  /// 文本长度  文本内容
  Function? callback;
  // bool isFocus;
  FocusNode? focusNode;
  final String hintText;

  @override
  State<InputMobile> createState() => _InputMobileState();
}

class _InputMobileState extends State<InputMobile> {

  TextEditingController controller = TextEditingController();
  ///type 0 不显示 clear 按钮，1显示
  int type = 0;
  bool isContinue = true;
  String lastText = '';
  @override
  void initState() {

    controller.addListener(() {
      if (controller.text.length - 2 >= lastText.length) {
        controller.text = lastText;
        return;
      }
      if (!isContinue) {
        isContinue = true;
        return;
      }
      if (controller.text.isEmpty)  return;
      var text = controller.text;
      String last = text.substring(text.length-1, text.length);
      if (last != '0' && last != '1' && last != '2'
          && last != '3' && last != '4' && last != '5'
          && last != '6' && last != '7' && last != '8' && last != '9') {
        isContinue = false;
        controller.text = text.substring(0, text.length-1);
        lastText = controller.text;
        return;
      }
      lastText = controller.text;
      var num = -1;
      type = 0;

      if (text.isNotEmpty) {
        num = text.length;
        type = 1;
      }

      if (widget.callback != null) {
        widget.callback!(num, text);
      }

    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(bottom: 15.0.h),
      child: Column(
        children: [
          Row(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Image.asset(loginNameIcon, width: 12.3.w, height: 17.3.h),
              HorPadding(10.w),
              Expanded(
                  child: Column(
                    children: [
                      TextField(
                        maxLength: 11,
                        maxLines: 1,
                        cursorColor: hintColor,
                        focusNode: widget.focusNode,
                        keyboardType: TextInputType.phone,
                        style: TextStyle(fontSize: 14.w, color: F1TextColor),
                        controller: controller,
                        decoration: InputDecoration(
                            border: InputBorder.none, // 取消输入框的下划线
                            counterText: '',
                            hintText: widget.hintText,
                            hintStyle: TextStyle(
                                color: hintColor
                            )
                        ),
                      ),
                    ],
                  )
              ),
              HorPadding(10.w),
              GestureDetector(onTap: (){
                controller.clear();

                if (widget.callback != null) {
                  widget.callback!(-1, '');
                }

              }, child: Offstage(offstage: type == 0, child: Image.asset(clearNameIcon, width: 14.3.w, height: 14.3.w))),
              HorPadding(5.w)
            ],
          ),
          Divider(
            height: 0.5.h,
            color: lineColor,
          )
        ],
      ),
    );
  }
}


